package main

import (
	"flag"
	"io"
	"net/http"
	"os"
	"path"
	"showdocApi/logs"
	"showdocApi/markdown"
	"strings"
)

func main() {
	var (
		swagger, showDocHost, apiKey, apiToken string
		jsonBody                               []byte
		err                                    error
	)
	flag.StringVar(&swagger, "swagger", "", "可用的Swagger JSON http(s)地址或swagger.json文件的绝对路径")
	flag.StringVar(&showDocHost, "host", "", "show-doc服务器地址,可以是一个IP+PORT地址，也可以是一个域名地址,例:http://127.0.0.1:8080或http://www.baidu.com")
	flag.StringVar(&apiKey, "key", "", "api_key，认证凭证。登录show-doc，进入具体项目后，点击右上角的”项目设置”-“开放API”便可看到")
	flag.StringVar(&apiToken, "token", "", "api_token,认证凭证。登录show-doc，进入具体项目后，点击右上角的”项目设置”-“开放API”便可看到")
	flag.Parse()
	if swagger == "" || showDocHost == "" || apiKey == "" || apiToken == "" {
		logs.Error("parameters are missing")
		return
	}
	if strings.HasPrefix(swagger, "https://") || strings.HasPrefix(swagger, "http://") {
		rep, err := http.Get(swagger)
		if err != nil {
			logs.Error(err)
			return
		}
		if rep.StatusCode == 200 {
			jsonBody, err = io.ReadAll(rep.Body)
			if err != nil {
				logs.Error(err)
				return
			}
		}
	} else {
		dir, err := os.Getwd()
		if err != nil {
			logs.Error("获取当前工作目录失败:", err)
			return
		}
		jsonBody, err = os.ReadFile(path.Join(dir, swagger))
		if err != nil {
			logs.Error(err.Error())
			return
		}
	}
	resolver, err := markdown.Init(jsonBody, apiKey, apiToken, showDocHost)
	if err != nil {
		panic(err.Error())
	}
	if err = resolver.Generate(); err != nil {
		logs.Error(err.Error())
	}
	logs.Info("SUCCESS---------------------------END")
}
